# -*- codeing = utf-8 -*-
# @Time : 2021/1/1 16:45
# File : jiqiren.py

import requests
import os

#生成Session对象，用于保存Cookie
s = requests.Session()

#登录豆瓣
login_url  = "https://accounts.douban.com/j/mobile/login/basic"
#请求头
headers = {'User-Agent':'Mozilla/5.0', 'Referer':'https://accounts.douban.com/passport/login_popup?login_source=anony'}
#传递用户名和密码
data = {
    'name':'13570716079',
    'password': 'lan7712213',
    'remember':'true'
}
try:
    r = s.post(login_url, headers=headers, data=data)
    r.raise_for_status()
except:
    print('爬取失败')

#打印请求结果
print(r.text)

def spider_comment(start=0):
    """
    爬取某页影评
    :param start: 起始位置，相当于分页参数
    :return:
    """
    comment_url = 'https://movie.douban.com/subject/30171424/comments?start=0&limit=20&status=P&sort=new_score'
    #请求头
    headers = {'User-Agent':'Mozilla/5.0'}
    try:
        r = s.get(comment_url, headers=headers)
        r.raise_for_status()
    except:
        print("爬取失败")
    #写入数据前先清空之前的数据
    if os.path.exists('douban.txt'):
        os.remove('douban.txt')
    with open('douban.txt', "a+", encoding=r.encoding) as file:
        file.write(r.text)

if __name__ == '__main__':
    spider_comment()